package view.wizard;

import java.util.Vector;

import javax.microedition.lcdui.Command;

/**
 * The Wizard views container 
 * 
 * @author Marcelo
 */
public class WizardEngine {

	private Vector wzdViews = new Vector();

	public void addWizardView(WizardView view) {
		wzdViews.addElement(view);
	}
	
	public boolean isFirst(WizardView view) {
		return wzdViews.indexOf(view) == 0;
	}
	
	public boolean isLast(WizardView view) {
		return wzdViews.indexOf(view) == wzdViews.size()-1;
	}
	
	public void startWizard() {
		if(wzdViews.size()>0) {
			WizardView next_view = (WizardView) wzdViews.elementAt(0);
			showView(next_view);
	    }
	}
	
	private void showView(WizardView wzdView) {
		wzdView.setEngine(this);
		wzdView.showScreen();
	}

	public void wizardCmdAction(Command command, WizardView curWzdView) {
		int viewIndex = wzdViews.indexOf(curWzdView);
		
		if(command == WizardView.NEXT_COMMAND) {
			if(viewIndex < wzdViews.size() - 1) {
				if(curWzdView.onLeave(WizardView.DIR_FORWARD) != WizardView.OK)
					return;

				WizardView next_view = (WizardView) wzdViews.elementAt(viewIndex + 1);
				if(next_view.onEnter(WizardView.DIR_FORWARD) != WizardView.OK)
					return;

				showView(next_view);
			}
		}

		else if (command == WizardView.BACK_COMMAND) {
			if(viewIndex > 0) {
				WizardView prev_view = (WizardView) wzdViews.elementAt(viewIndex-1);
				if (curWzdView.onLeave(WizardView.DIR_BACKWARD) != WizardView.OK)
					return;
				if (prev_view.onEnter(WizardView.DIR_BACKWARD) != WizardView.OK)
					return;

				showView(prev_view);
			}
		}
	}

}